import {
  findAcOrOrgList, //获取所有秘钥以及下属
  findOrgAll,
  findSerialAll, //广告系列组
  findCampaign, //campaign
  findAdgroupsList, //查询所有的Ad
} from '@/api/overView'
import Cookies from 'js-cookie'
import {
  resetRouter
} from '@/router'

import {
  getToDay,
  getYesDay,
  getTime,
  getAbout7Day,
  getThisWeek,
  getThisMonth,
  getThisYear,
  getThisYearToDay,
  getAbout7DayToDay
} from '@/utils/moment.js'


const initTime = (type) => {
  const obj = Cookies.get('Choose-time') ? JSON.parse(Cookies.get('Choose-time')) : undefined
  if (obj) {
    if (obj.timeChooseType) {
      // 要是有时间类型
      return chooseTimeType({
        val: obj.timeChooseType
      })
    } else {
      let timeobj = {
        startTime: getTime(new Date(obj.startTime)),
        endTime: getTime(new Date(obj.endTime))
      }
      return timeobj
    }
  } else {
    return chooseTimeType({
      val: '7day'
    })
  }
}

// 点击了昨日，本周，本月等按钮改变了时间
const chooseTimeType = (item) => {
  const val = item.val
  var timeObj = undefined
  switch (val) {
    case 'today':
      timeObj = getToDay()
      break
    case 'yestoday':
      timeObj = getYesDay()
      break
    case 'week':
      timeObj = getThisWeek()
      break
    case '7day':
      timeObj = getAbout7Day()
      break
    case 'month':
      timeObj = getThisMonth()
      break
    case 'year':
      timeObj = getThisYear()
      break
  }

  return timeObj

}

const initTime1 = function() {

  let obj = JSON.parse(localStorage.getItem('YYY_Time_Obj'));
  if (obj.overViewTimeType) {
    obj.overViewTime = chooseTimeType({
      val: obj.overViewTimeType
    })
  }
  if (obj.financeTimeType) {
    obj.financeTime = chooseTimeType({
      val: obj.financeTimeType
    })
  }
  return obj
}

const getDefaultState = () => {
  return {
    allAc: localStorage.getItem('YYY_ALLAC') ? JSON.parse(localStorage.getItem('YYY_ALLAC')) : [], //所有的秘钥
    allOrg: localStorage.getItem('YYY_ALLORG') ? JSON.parse(localStorage.getItem('YYY_ALLORG')) : [], //所有的Org
    allSerial: localStorage.getItem('YYY_ALLSERIAL') ? JSON.parse(localStorage.getItem('YYY_ALLSERIAL')) : [], //所有广告系列组
    allCa: localStorage.getItem('YYY_ALLCA') ? JSON.parse(localStorage.getItem('YYY_ALLCA')) : [], //所有的campaign;
    allAd: localStorage.getItem('YYY_ALLAD') ? JSON.parse(localStorage.getItem('YYY_ALLAD')) : [], //所有的adgroup;
    typeTime: initTime(),
    timeObj: localStorage.getItem('YYY_Time_Obj') ? initTime1() : {
      overViewTimeType: '7day', //数据概览页面选中的日期类型
      overViewTime: getAbout7Day(), //数据概览页面选中的具体日期
      financeTimeType: '7day', //
      financeTime: getAbout7DayToDay()
    }
  }
}

const state = getDefaultState();
const mutations = {

  // 重新存储所有秘钥信息
  SET_ALLAC: (state, arr) => {
    localStorage.setItem('YYY_ALLAC', JSON.stringify(arr));
    state.allAc = arr
  },


  // 重新存所有Org信息
  SET_ALLORG: (state, arr) => {
    localStorage.setItem('YYY_ALLORG', JSON.stringify(arr));
    state.allOrg = arr
  },


  // 重新获取所有广告系列组
  SET_ALLSerial: (state, arr) => {
    localStorage.setItem('YYY_ALLSERIAL', JSON.stringify(arr));
    state.allSerial = arr
  },

  // 重新存储所有的campaign信息
  SET_ALLCA: (state, arr) => {
    localStorage.setItem('YYY_ALLCA', JSON.stringify(arr));
    state.allCa = arr
  },
  // 重新存储所有的ad信息
  SET_ALLAD: (state, arr) => {
    localStorage.setItem('YYY_ALLAD', JSON.stringify(arr));
    state.allAd = arr;
  },
  // 修改所有的campaign信息的其中一个campaign信息
  EDIT_ONE_CA: (state, obj) => {
    // state.name = name
  },

  SET_TYPE_TIME: (state, obj) => {
    Cookies.set('Choose-time', obj)
    state.typeTime = obj;
  },

  // 重新设置选择的时段
  SET_YYY_Time: (state, obj) => {
    localStorage.setItem('YYY_Time_Obj', JSON.stringify(obj))
    state.timeObj = obj;
  }
}

const actions = {
  getAllAc({
    commit,
    state
  }, queryData) {
    return new Promise((resolve, reject) => {
      // 清空秘钥
      commit('SET_ALLORG', []);
      commit('SET_ALLCA', []);
      // 清空广告系列

      findAcOrOrgList({ ...queryData
      }).then(response => {
        const {
          data
        } = response;

        if (data.code === 20000) {

          let list = data.data.map(item => {
            if (item.org && item.org.length) return item;
          })
          commit('SET_ALLAC', list);
          resolve(list)
        } else {
          reject(error)
        }


      }).catch(error => {
        reject(error)
      })
    })
  },

  getAllOrg({
    commit,
    state
  }, queryData) {
    return new Promise((resolve, reject) => {
      // 清空秘钥
      commit('SET_ALLORG', []);
      commit('SET_ALLCA', []);
      // 清空广告系列
      findOrgAll({ ...queryData
      }).then(response => {
        const {
          data
        } = response;
        if (data.code === 20000) {
          commit('SET_ALLORG', data.data);
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },


  // 获取所有的广告系列组
  getAllSerial({
    commit,
    state
  }, queryData) {
    return new Promise((resolve, reject) => {
      findSerialAll({ ...queryData
      }).then(response => {
        const {
          data
        } = response;
        if (data.code === 20000) {
          commit('SET_ALLSerial', data.data);
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },


  // 获取所有的campaign;
  getAllCampaign({
    commit,
    state
  }, queryData) {
    return new Promise((resolve, reject) => {
      findCampaign({ ...queryData
      }).then(response => {
        const {
          data
        } = response;
        if (data.code === 20000) {
          commit('SET_ALLCA', data.data);
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取所有的AdGroup
  getAllAdgroup({
    commit,
    state
  }, queryData) {
    return new Promise((resolve, reject) => {
      findAdgroupsList({ ...queryData
      }).then(response => {
        const {
          data
        } = response;
        // console.log(response, data, '回来的数据// 获取所有的AdGroup')
        if (data.code === 20000) {
          commit('SET_ALLAD', data.data);
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  editOneCa({
    commit,
    state
  }, obj) {
    let arr = JSON.parse(JSON.stringify(state.allCa));
    let index = arr.findIndex(item => {
      return item.campaignId === obj.campaignId
    })
    arr[index] = obj;
    commit('SET_ALLCA', arr);
  },



  editOneAd({
    commit,
    state
  }, obj) {
    let arr = JSON.parse(JSON.stringify(state.allAd));
    // console.log(arr, '修改前')
    let index = arr.findIndex(item => {
      return item.adGroupId === obj.adGroupId
    })
    arr[index] = obj;
    commit('SET_ALLAD', arr);
    // console.log(state, '修改后')
  },

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
